<?php

namespace app\admin\service;

use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use think\admin\Service;
use think\facade\Db;
use think\facade\Log;

/**
 * 企业微信OA服务
 * Class WxWorkOAService
 * @package app\data\service
 */
class WxWorkOAService extends Service
{
    /**
     * 小程序配置参数
     * @var array
     */
    private $config;
    private $contacts;

    /**
     * 接口服务初始化
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function initialize()
    {
        $this->config = config('office_work');
        $this->config = [
            'corp_id' => $this->config['corp_id'],
            'secret' => $this->config['check_in_agent_secret'],
            'agent_id' => $this->config['check_in_agent_id'],
        ];
        $this->contacts = Factory::work($this->config);
    }

    /**
     * 获取打卡日报数据
     */
    public function checkInRecords(int $startTime, int $endTime, array $user, $type = 3)
    {
//        $type: 打卡类型 1：上下班打卡；2：外出打卡；3：全部打卡
        try {
            $result = $this->contacts->oa->checkinRecords($startTime, $endTime, $user, $type);
            foreach ($result['checkindata'] ?? [] as $item) {
                if (in_array($item['checkin_type'], ['上班打卡', '外出打卡'])) {
                    if ($item['exception_type'] != '未打卡') {
                        $users[] = $item['userid'];
                    }
                }
            }

        } catch (\Exception $exception) {
            Log::error('获取打卡信息失败' . $exception->getMessage());
        }

        return array_unique($users ?? []);
    }
}